package com.oritsh.dicom.wado.controller;

import com.oritsh.dicom.exception.DicomException;
import com.oritsh.dicom.service.CGetService;
import com.oritsh.dicom.service.CMoveService;
import com.oritsh.dicom.utils.DataSetHelper;
import com.oritsh.dicom.utils.ImageHelper;
import com.oritsh.dicom.wado.service.HTTPDicomGet;
import org.dcm4che.data.Attributes;
import org.dcm4che.io.DicomInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zarra
 * Date: 14-2-6
 * Time: 上午9:46
 * Copyright Shanghai Orient Rain Information Technology Co.,Ltd.
 */
@RequestMapping("wado")
@Controller
public class WADOController {

    Logger logger = LoggerFactory.getLogger(WADOController.class);

    //@Autowired
    //CGetService getService;

    @Autowired
    HTTPDicomGet cget;

    @Autowired
    @Qualifier("moveService")
    CMoveService moveService;

    @Autowired
    @Qualifier("moveService2")
    CMoveService moveService2;

    static public final String dicomMimetype = "application/dicom";



    public DicomInputStream dicomInputStream(String studyUID, String seriesUID, String objectUID){
        DicomInputStream inputStream = null;
        try {
            try {
                inputStream = moveService2.cmove(studyUID, seriesUID, objectUID, false);
            }catch (Exception e){
                inputStream = null;
            }

            logger.info("inputStream!!!!!!! = "+inputStream);
            if (inputStream!=null && inputStream.length() > 0) {
                return inputStream;
            } else {
                moveService.cmove(studyUID, seriesUID, objectUID, true);
                int retry = 0;
                do {
                    try {
                        inputStream = moveService2.cmove(studyUID, seriesUID, objectUID, false);
                    }catch (Exception e){
                        inputStream = null;
                    }
                    retry++;
                    logger.info("retry:" + retry);
                } while (inputStream != null && inputStream.length() <= 0 && retry < 10);
            }
            return inputStream;
        }catch (Exception e){
            e.printStackTrace();
            logger.info(e.getMessage());
            return null;
        }
    }

    //example
    // http://javaee.oritsh.com/wado-service/wado?requestType=WADO&studyUID=1.2.840.113820.862126.128.120140202000618&seriesUID=1.2.392.200036.9116.2.5.1.48.1224104559.1391267248.457959&objectUID=1.2.392.200036.9116.2.5.1.48.1224104559.1391267264.175043&annotation=patient,technique,institution
    @RequestMapping(value = "", method = RequestMethod.GET, params = "requestType=WADO")
    public void wado(
            @RequestParam(value = "studyUID") String studyUID,
            @RequestParam(value = "seriesUID") String seriesUID,
            @RequestParam(value = "objectUID") String objectUID,
            @RequestParam(value = "contentType", required = false, defaultValue = "image/jpeg") String contentType,
            @RequestParam(value = "annotation", required = false, defaultValue = "") String annotation,
            HttpServletResponse response)
            throws DicomException, IOException {
        response.setContentType(contentType);
        //InputStream in = cget.cget(objectUID);
        //byte[] buffer = FileCopyUtils.copyToByteArray(in);

        try (DicomInputStream inputStream = dicomInputStream(studyUID, seriesUID, objectUID)/*new DicomInputStream(new ByteArrayInputStream(buffer))*/) {

            if (inputStream == null)
                return;

            if (contentType.equals(dicomMimetype)) {
                response.addHeader("Content-Disposition","attachment;filename="+ objectUID);
                FileCopyUtils.copy(inputStream, response.getOutputStream());
            } else {
                BufferedImage image = ImageHelper.dcm2pic(inputStream);
                if (annotation.length() > 0) {
                    image = ImageHelper.imageCopy(image);
                    DicomInputStream is = moveService2.cmove(studyUID,seriesUID,objectUID,false);
                    Attributes datasets = DataSetHelper.attributesFromInputStream(is);
                    List<String> splits = Arrays.asList(annotation.split(","));
                    if (splits.contains("patient"))
                        image = ImageHelper.imageAddPatientAnnotation(image, datasets);
                    if (splits.contains("technique"))
                        image = ImageHelper.imageAddStudyAnnotation(image, datasets);
                    if (splits.contains("institution"))
                        image = ImageHelper.imageAddInstitutionAnnotation(image, datasets);
                    is.close();
                }
                ImageHelper.saveImage(image, response.getOutputStream(), contentType);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                moveService2.cmove(studyUID,seriesUID,objectUID,true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
